<script setup name="fieldConfig">
import { GetMenuPageAPI } from '@/api/system/printConfig'

import { ConfigFieidAPI, GetDetailsAPI } from '@/api/system/printConfig.js'
import xiaoheTable from '@/components/XiaoheComponents/table/index.vue'
import { reactive, watch } from 'vue'

const assist = ref(false)
const { proxy } = getCurrentInstance()
const route = useRoute()
const router = useRouter()
//  树结构 页面数据
const menuPage = ref([])
// 获取列表
const getMenuPage = async () => {
  try {
    const res = await GetMenuPageAPI()
    console.log(res.data, 'res.data')

    menuPage.value = res.data
  } catch (error) {
  } finally {
  }
}

getMenuPage()

// 页面位置
const menuPageValue = ref()

// 加载状态
const loading = ref(false)
// 列表数据
const tableData = ref([
  {
    printName: '',
    printField: '',
    printType1: 'text'
  }
])

/**
 * 自定义表格数据
 */
const tableList = ref([{}])

/**
 * 自定义列表表头数据
 */
const columnList = ref([])

/**
 * 表单表头数据
 */
const arrList = ref([
  { label: '物料编码', value: 'materialCode' },
  { label: '物料名称', value: 'materialName' },
  { label: '物料规格', value: 'materialType' }
])

/**
 * 自定义表单数据
 */
const form = reactive({ a: '' })

/**
 * 自定义表头表单弹窗状态
 */
const show = ref(false)

// 下拉状态
const selList = ref([
  {
    label: '普通文本',
    value: 'text'
  },
  {
    label: '二维码',
    value: 'qrcode'
  },
  {
    label: '条形码',
    value: 'barcode'
  },

  {
    label: '图片',
    value: 'image'
  }
])

// 加载状态
const btnLoading = ref(false)
const tabSel = ref([])
const handleSelectionChange = row => {
  tabSel.value = row
}

//  弹窗
const getDailt = async () => {
  try {
    proxy.$modal.loading('请稍候...')
    loading.value = true
    const { data: res } = await GetDetailsAPI(menuPageValue.value)
    tableData.value = res.map(item => ({
      printName: item.title,
      printField: item.tid,
      printType1: item.options.textType ? item.options.textType : 'text'
    }))
  } catch {
  } finally {
    loading.value = false
    proxy.$modal.closeLoading()
  }
}
// 保存
const submit = async () => {
  if (!menuPageValue.value) return proxy.warningMsg('请选择要配置的页面位置！')

  const isif = tableData.value.every(item => item.printName && item.printField)
  if (!isif) return proxy.warningMsg('字段名称和字段变量都必填')
  await tableData.value.forEach(item => {
    item.printId = route.query.id
    item.printCorrelation = menuPageValue.value

    if (item.printType1 == 'text') {
      item.icon = 'wenben'
      item.printType = 'text'
    }
    if (item.printType1 == 'qrcode') {
      item.icon = 'erweima'
      item.textType = 'qrcode'
      item.printType = 'text'
    }
    if (item.printType1 == 'barcode') {
      item.icon = 'tiaoxingma'
      item.textType = 'barcode'
      item.printType = 'text'
    }
    if (item.printType1 == 'image') {
      item.icon = 'tupian'
      item.textType = 'image'
      item.printType = 'image'
    }
  })
  proxy.$modal.loading('请稍候...')
  try {
    btnLoading.value = true
    await ConfigFieidAPI(tableData.value)
    proxy.successMsg('操作成功!')
    tableData.value = []
    getDailt()
  } catch {
  } finally {
    btnLoading.value = false
    proxy.$modal.closeLoading()
  }
}

// 重置
const reset = scope => {
  tableData.value.splice(scope.$index, 1, {
    printName: '',
    printField: '',
    printType1: 'text'
  })
}

// 添加、当前下的添加
const add = scope => {
  if (scope) {
    tableData.value.splice(scope.$index + 1, 0, {
      printName: '',
      printField: '',
      printType1: 'text'
    })
  } else {
    tableData.value.push({
      printName: '',
      printField: '',
      printType1: 'text'
    })
  }
}

const remove = scope => {
  if (tabSel.value.length > 0) {
    tabSel.value.forEach(item => {
      const Find = tableData.value.findIndex(
        itemy => item.printType1 == itemy.printType1 && item.printField == itemy.printField
      )
      tableData.value.splice(Find, 1)
    })
  } else {
    tableData.value.splice(scope.$index, 1)
  }
}

const change = val => {
  // 校验字段变量不能是纯数字！

  if (/^\d+$/.test(val.row.printField)) {
    proxy.warningMsg('字段变量不能是纯数字！')
    tableData.value[val.$index].printField = ''
    return
  }

  // 校验字段变量不能有特殊符号！
  if (/[.*+?^${}()|[]]/g.test(val.row.printField)) {
    proxy.warningMsg('字段变量不能有特殊符号！')
    tableData.value[val.$index].printField = ''
    return
  }

  // 校验变量唯一
  // let i = 0
  // tableData.value.forEach(item => {
  //   if (item.printField == val.row.printField && item.printType1 == val.row.printType1) i++
  // })

  // if (i > 1) {
  //   proxy.warningMsg('字段类型、变量的数据已存在，请换个变量名称！！！')

  //   tableData.value[val.$index].printField = ''
  // }
}

// 向上排序
const up = scope => {
  window.localStorage.setItem('as', JSON.stringify(scope.row))
  // tableData.value.unshift([0])
  if (scope.$index >= 1) {
    const Obj = JSON.parse(window.localStorage.getItem('as'))
    tableData.value.splice(scope.$index - 1, 0, Obj)
    tableData.value.splice(scope.$index + 1, 1)
  } else {
    tableData.value.push(tableData.value.shift())
  }
  submit()
}

// 向下排序
const downward = scope => {
  // console.log(tableData.value[scope.$index + 1])
  if (scope.$index != tableData.value.length - 1) {
    window.localStorage.setItem('as', JSON.stringify(scope.row))
    const Obj = JSON.parse(window.localStorage.getItem('as'))
    tableData.value.splice(scope.$index + 2, 0, Obj)
    tableData.value.splice(scope.$index, 1)
  } else {
    tableData.value.unshift(tableData.value.pop())
  }

  submit()
}

const tab = [
  {
    th: '字段名称',
    key: 'printName',
    width: 150
  },
  {
    th: '字段变量',
    key: 'printField',
    width: 120
  },
  {
    th: '类型',
    key: 'printType1',
    type: 'btn'
  }
]

/**
 * 关闭当前页面
 */
const backTo = async () => {
  const result = await proxy.MessageBox('返回页面，数据会销毁，请确认数据已保存')
  if (!result) return
  router.push('/system/printConfig')
}

/**
 * 表格添加
 */
const addarrList = () => {
  show.value = true
}

/**
 * 表头下拉改变事件
 * @param val
 */
const Change = val => {
  const Obj = arrList.value.find(itemy => itemy.value == val)
  form.b = Obj.label
}

/**
 * 表格添加-行
 */
const addList = () => {
  if (columnList.value.length == 0) return proxy.warningMsg('请先添加表头')
  tableList.value.push({})
}

/**
 * 添加表头
 */
const addOK = () => {
  const newColumnLabel = form.a
  const name = form.b
  if (newColumnLabel) {
    const exists = columnList.value.some(col => col.label === name)
    if (!exists) {
      const newKey = newColumnLabel.toLowerCase().replace(/\s+/g, '_')
      columnList.value.push({ label: name, value: newKey })
      tableList.value.forEach(item => {
        item[newKey] = '1'
      })
    }
  }
  show.value = false
}

// 引导
onMounted(() => {
  menuPageValue.value = Number(route.query.printCorrelation)
  getDailt()
})
</script>

<template>
  <div class="app-container">
    <div class="flex-between">
      <!-- <el-cascader
        v-model="menuPageValue"
        :options="menuPage"
        :props="{
          label: 'menuName',
          value: 'menuId',
          children: 'children'
        }"
        @change="getDailt"
      /> -->
      <el-tree-select
        ref="treeRef"
        v-model="menuPageValue"
        :data="menuPage"
        default-expand-all
        node-key="menuId"
        :props="{
          label: 'menuName',
          value: 'menuId',
          children: 'children'
        }"
        @change="getDailt(menuPageValue)"
      />
      <div>
        <el-popover
          placement="top-start"
          title="提示"
          :width="400"
          trigger="hover"
          content="根据左侧页面位置，查询字段内容。如没有字段需选择页面位置，添加字段点击保存。"
        >
          <template #reference>
            <el-button @click="assist = true">帮助</el-button>
          </template>
        </el-popover>

        <el-button @click="add(false)">添加一条</el-button>
        <el-button @click="submit">保存</el-button>
        <el-button @click="backTo">返回</el-button>
      </div>
    </div>

    <!-- <xiaoheTable :tableData="tab" :data="tableData" /> -->
    <!-- <TransitionGroup name="fade" tag="tbody" class="container"> -->
    <el-table :data="tableData" stripe border style="margin-top: 20px" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column fixed type="index" label="序号" width="60" />
      <el-table-column label="字段名称" width="auto">
        <template #default="scope">
          <el-input v-model="scope.row.printName"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="字段变量" width="auto">
        <template #default="scope">
          <el-input v-model="scope.row.printField" @change="change(scope)"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="类型" width="auto">
        <template #default="scope">
          <el-select v-model="scope.row.printType1" clearable placeholder="请选择你要的类型">
            <el-option v-for="(item, index) in selList" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-link type="primary" text="重置" @click="reset(scope)" />
          <el-link type="primary" text="删除" @click="remove(scope)" />
          <el-link type="primary" text="添加" @click="add(scope)" />
          <el-link type="primary" text="向上" @click="up(scope)" />
          <el-link type="primary" text="向下" @click="downward(scope)" />
        </template>
      </el-table-column>
    </el-table>
    <!-- </TransitionGroup> -->

    <p-XiaoheDialog :dialogVisible="assist" title="提示" @close="assist = false" width="60%">
      <template #body>
        <img src="../../../assets/images/12.png" alt="" />
      </template>
    </p-XiaoheDialog>

    <!-- 自定义表格 -->
    <!-- <div style="text-align: center; cursor: pointer" @click="addarrList">+添加表头</div>
    <el-table
      border
      :data="tableList"
      style="width: 100%"
      :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column :label="col.label" v-for="(col, colIndex) in columnList" :key="colIndex" width="auto">
        <template #default="scoped">
          <el-input clearable v-model="scoped.row[col.value]" />
        </template>
      </el-table-column>
    </el-table>
    <div>{{ tableList }}</div>
    <div>{{ columnList }}</div> -->
    <!-- 自定义表头弹窗 -->
    <p-dialog v-model="show" width="20rem" title="添加表头" @ok="addOK" @close="closeList">
      <template #body>
        <el-form ref="addFormRef" :model="form" status-icon>
          <el-form-item label="表头列数据">
            <p-select v-model="form.a" :option="arrList" @change="Change" placeholder="请选择一个表头" />
          </el-form-item>
        </el-form>
      </template>
    </p-dialog>
  </div>
</template>

<style lang="scss" scoped>
.container {
  position: relative;
  padding: 0;
  width: 100%;
}

/* 1. 声明过渡效果 */
.fade-move,
.fade-enter-active,
.fade-leave-active {
  transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
}

/* 2. 声明进入和离开的状态 */
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: scaleY(0.01) translate(30px, 0);
}

/* 3. 确保离开的项目被移除出了布局流
      以便正确地计算移动时的动画效果。 */
.fade-leave-active {
  position: absolute;
}
</style>
